package com.lanyou.cook.entity.domain;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.Version;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.lanyou.cook.common.DefaultDateJsonDeserializer;
import com.lanyou.cook.common.DefaultDateJsonSerializer;
import com.lanyou.cook.datadictionary.KettleJobExecServerType;
import com.lanyou.cook.datadictionary.KettleJobScheduleCycleUnit;
import com.lanyou.cook.datadictionary.KettleJobScheduleStatus;
import com.lanyou.cook.service.DataDictionaryService;

@Entity
@EntityListeners({ AuditingEntityListener.class, InterfaceScheduleEntityListener.class})
@Table(name = "T_COOK_BU_JOB_SCHEDULE")
public class InterfaceSchedule implements Serializable {
	
	
	@PrePersist
	void initDefaultValue(){
		runStatus = KettleJobScheduleStatus.Off.ValueCode;
	}
	
	// 调度ID
	private String id;
	
	private int version;

	// 调度名称
	private String name;

	// 错误通知者
	private String errSendTo;

	// 执行周期单位
	private String runWay;
	
	// 执行周期
	private int runCyc;

	// 周执行日
	private String dayOfWeek;

	// 执行状态
	private String runStatus;

	// 开始日期
	private Date beginTime;

	// 结束日期
	private Date endTime;

	// 上一次执行时间
	private Date lastRunTime;

	// 下一次执行时间
	private Date nextRunTime;
	
	//作业执行超时时长
	private int overTimes;

	// 备注
	private String remark;

	private String creator;

	private String modifier;

	private Date createTime;

	private Date modifyTime;
	
	private String sendEmailType;//异常邮件发送类型1：实时；0：定时
	
	
	private String errSendToFail;//错误发送者邮箱失效通知人
	
	private Integer maxSendEmailNum;//连续失败发送邮件上限
	
	private String isAgainExecutJob;//是否在失败后自动调度1：是，0：否
	
	private Integer failedNum;//已经连续失败次数

	private transient SystemInterface systemInterface;

	private transient InterfaceScheduleServer scheduleServer;
	
	// 用于在EntityListener中访问实体修改前的值
    transient InterfaceSchedule original;
	
    public final static Specification<InterfaceSchedule> EmptySpecification = new Specification<InterfaceSchedule>(){
		@Override
		public Predicate toPredicate(Root<InterfaceSchedule> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
			return null;
		}
	};
	
	public static Specification<InterfaceSchedule> idSpecification(String id){
		return new Specification<InterfaceSchedule>(){
			@Override
			public Predicate toPredicate(Root<InterfaceSchedule> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				query.where(cb.equal(root.get("id"), id));
				return null;
			}
		};
	}
	
	@Id
	@GeneratedValue(generator = "uuidGenerator")
	@GenericGenerator(name = "uuidGenerator", strategy = "uuid")
	@Column(name = "JOB_SCHEDULE_ID", length = 36)
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	@Version
	@JsonIgnore
	public int getVersion() {
		return version;
	}

	public void setVersion(int version) {
		this.version = version;
	}

	@Column(name = "JOB_SCHEDULE_NAME", nullable = false, unique = true, length = 50)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Column(name = "ERR_SEND_TO", length = 100)
	public String getErrSendTo() {
		return errSendTo;
	}

	public void setErrSendTo(String errSendTo) {
		this.errSendTo = errSendTo;
	}

	@Column(name = "RUN_WAY", length = DataDictionaryValue.MAX_LENGTH_OF_CODE)
	public String getRunWay() {
		return runWay;
	}

	public void setRunWay(String runWay) {
		this.runWay = runWay;
	}

	@Column(name = "RUN_CYC", length = 2)
	public int getRunCyc() {
		return runCyc;
	}

	public void setRunCyc(int runCyc) {
		this.runCyc = runCyc;
	}

	@Column(name = "DAY_Of_WEEK", length = 100)
	public String getDayOfWeek() {
		return dayOfWeek;
	}

	public void setDayOfWeek(String dayOfWeek) {
		this.dayOfWeek = dayOfWeek;
	}

	@Column(name = "RUN_STATUS", length = 2)
	public String getRunStatus() {
		return runStatus;
	}

	public void setRunStatus(String runStatus) {
		this.runStatus = runStatus;
	}

	@Column(name = "SKD_BEGIN_DATE")
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	@JsonDeserialize(using = DefaultDateJsonDeserializer.class)
	public Date getBeginTime() {
		return beginTime;
	}

	public void setBeginTime(Date beginTime) {
		this.beginTime = beginTime;
	}

	@Column(name = "SKD_END_DATE")
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	@JsonDeserialize(using = DefaultDateJsonDeserializer.class)
	public Date getEndTime() {
		return endTime;
	}

	public void setEndTime(Date endTime) {
		this.endTime = endTime;
	}

	@Column(name = "LAST_RUN_TIME")
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	public Date getLastRunTime() {
		return lastRunTime;
	}

	public void setLastRunTime(Date lastRunTime) {
		this.lastRunTime = lastRunTime;
	}

	@Column(name = "NEXT_RUN_TIME")
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	public Date getNextRunTime() {
		return nextRunTime;
	}

	public void setNextRunTime(Date nextRunTime) {
		this.nextRunTime = nextRunTime;
	}

	@Column(length = 100)
	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	@CreatedBy
	@Column(length = 50, updatable=false)
	public String getCreator() {
		return creator;
	}

	public void setCreator(String creator) {
		this.creator = creator;
	}

	@LastModifiedBy
	@Column(length = 50)
	public String getModifier() {
		return modifier;
	}

	public void setModifier(String modifier) {
		this.modifier = modifier;
	}

	@Column(name = "CREATED_DATE", updatable=false)
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	@CreatedDate
	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	@Column(name = "LAST_UPDATED_DATE")
	@JsonSerialize(using = DefaultDateJsonSerializer.class)
	@LastModifiedDate
	public Date getModifyTime() {
		return modifyTime;
	}

	public void setModifyTime(Date modifyTime) {
		this.modifyTime = modifyTime;
	}
	
	@Column(name = "OVER_TIMES")
	public int getOverTimes() {
		return overTimes;
	}

	public void setOverTimes(int overTimes) {
		this.overTimes = overTimes;
	}
	
	@Column(name = "SEND_EMAIL_TYPE")
	public String getSendEmailType() {
		return sendEmailType;
	}

	public void setSendEmailType(String sendEmailType) {
		this.sendEmailType = sendEmailType;
	}
	
	@Column(name = "ERR_SEND_TO_FAIL")
	public String getErrSendToFail() {
		return errSendToFail;
	}

	public void setErrSendToFail(String errSendToFail) {
		this.errSendToFail = errSendToFail;
	}

	@Column(name = "MAX_SEND_EMAIL_NUM")
	public Integer getMaxSendEmailNum() {
		return maxSendEmailNum;
	}

	public void setMaxSendEmailNum(Integer maxSendEmailNum) {
		this.maxSendEmailNum = maxSendEmailNum;
	}

	@Column(name = "IS_AGAIN_EXECUT_JOB")
	public String getIsAgainExecutJob() {
		return isAgainExecutJob;
	}

	public void setIsAgainExecutJob(String isAgainExecutJob) {
		this.isAgainExecutJob = isAgainExecutJob;
	}

	@Column(name = "FAILED_NUM")
	public Integer getFailedNum() {
		return failedNum;
	}

	public void setFailedNum(Integer failedNum) {
		this.failedNum = failedNum;
	}

	@ManyToOne
	@JoinColumn(name = "FIELD_JOB_ID")
	public SystemInterface getSystemInterface() {
		return systemInterface;
	}

	

	public void setSystemInterface(SystemInterface systemInterface) {
		this.systemInterface = systemInterface;
	}

	@OneToOne(optional = true, cascade = CascadeType.ALL, orphanRemoval = true)
	@JoinColumn(name = "RUN_SERVICE_SET_ID")
	public InterfaceScheduleServer getScheduleServer() {
		return scheduleServer;
	}

	public void setScheduleServer(InterfaceScheduleServer scheduleServer) {
		this.scheduleServer = scheduleServer;
	}

	@Transient
	public String getFieldName() {
		try {
			return (String) PropertyUtils.getProperty(systemInterface, "ownerFieldSystem.field.name");
		} catch (Exception e) {
			return null;
		}
	}
	
	@Transient
	public String getSystemInterfaceId() {
		try {
			return (String) PropertyUtils.getProperty(systemInterface, "id");
		} catch (Exception e) {
			return null;
		}
	}
	
	@Transient
	public String getFieldId() {
		try {
			return (String) PropertyUtils.getProperty(systemInterface, "ownerFieldSystem.field.id");
		} catch (Exception e) {
			return null;
		}
	}

	@Transient
	public String getFieldSystemName() {
		try {
			return (String) PropertyUtils.getProperty(systemInterface, "ownerFieldSystem.name");
		} catch (Exception e) {
			return null;
		}
	}
	@Transient
	public String getFieldSystemId() {
		try {
			return (String) PropertyUtils.getProperty(systemInterface, "ownerFieldSystem.id");
		} catch (Exception e) {
			return null;
		}
	}

	@Transient
	public String getInterfaceName() {
		try {
			return (String) PropertyUtils.getProperty(systemInterface, "jobName");
		} catch (Exception e) {
			return null;
		}
	}

	@Transient
	public String getCycleForDisplay() {
		if (StringUtils.equals(runWay, KettleJobScheduleCycleUnit.Once.ValueCode)) {
			return DataDictionaryService.getInstance().getValueName(KettleJobScheduleCycleUnit.TypeCode, runWay);
		} else {
			String cycleName = DataDictionaryService.getInstance()
					.getValueName(KettleJobScheduleCycleUnit.TypeCode, runWay);
			return runCyc + cycleName;
		}
	}
	
	@Transient
	public String getServerForDisplay(){
		try {
			String runWay = (String) PropertyUtils.getProperty(scheduleServer, "runWay");
			
			if (StringUtils.equals(runWay, KettleJobExecServerType.Cluster.ValueCode)) {
				return DataDictionaryService.getInstance().getValueName(KettleJobExecServerType.TypeCode, runWay);
			} else {
				String slaveId = (String) PropertyUtils.getProperty(scheduleServer, "id");
				if(StringUtils.isNotEmpty(slaveId)){
					return (String) PropertyUtils.getProperty(scheduleServer, "slaveServer.hostName");
				}else{
					return null;
				}
			}
			
		} catch (Exception e) {
			return null;
		}
	}
	
	@Transient
	public String getRunStatusForDisplay() {
		return DataDictionaryService.getInstance().getValueName(KettleJobScheduleStatus.TypeCode, runStatus);
	}
	
	@Transient
	public String getRemoteRunWay(){
		try {
			return (String) PropertyUtils.getProperty(scheduleServer, "runWay");
		} catch (Exception e) {
			return null;
		}
	}
	
}
